package com.polaris.live.utils

import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager

/**
 * RecyclerUtils
 *
 * @author Created by lucas on 2023/10/21 13:47
 */
object RecyclerUtils {

    /**
     * 获取第一个View的索引
     */
    fun RecyclerView.getFirstPosition(): Int? {
        return layoutManager?.getFirstPosition()
    }

    /**
     * 获取第一个View的索引
     */
    fun RecyclerView.LayoutManager.getFirstPosition(): Int {
        return if (this is GridLayoutManager) {
            findFirstVisibleItemPosition()
        } else if (this is LinearLayoutManager) {
            findFirstVisibleItemPosition()
        } else if (this is StaggeredGridLayoutManager) {
            val staggeredLayoutManager = this
            staggeredLayoutManager.findFirstVisibleItemPositions(null)[0]
        } else {
            throw RuntimeException("Unsupported layoutManager ${this.javaClass.simpleName}")
        }
    }

    /**
     * 获取最后一个View的索引
     */
    fun RecyclerView.getLastPosition(): Int? {
        return layoutManager?.getLastPosition()
    }

    /**
     * 获取最后一个View的索引
     */
    fun RecyclerView.LayoutManager.getLastPosition(): Int {
        return if (this is GridLayoutManager) {
            findLastVisibleItemPosition()
        } else if (this is LinearLayoutManager) {
            findLastVisibleItemPosition()
        } else if (this is StaggeredGridLayoutManager) {
            val staggeredLayoutManager = this
            staggeredLayoutManager.findLastVisibleItemPositions(null)[staggeredLayoutManager.spanCount - 1]
        } else {
            throw RuntimeException("Unsupported layoutManager ${this.javaClass.simpleName}")
        }
    }
}